package com.free4k.keepalive.netty.hander;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.free4k.keepalive.constant.LapiUriConstat;
import com.free4k.keepalive.manager.HttpKeepAliveManager;
import com.free4k.keepalive.manager.RequestDeviceManager;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RePersonInfoServiceImpl implements IRePersonInfoService
{
    @Autowired
    private RePersonInfoMapper rePersonInfoMapper;

    @Autowired
    private IReSitePersonnelRelationService iReSitePersonnelRelationService;

    @Autowired
    private IReMachineService iReMachineService;

    @Value("${file.prefix}")
    public String localFilePrefix;

    @Value("${file.path}")
    public String filePath;

    //同步的人员列表
    private List<SyncResult> resultList = new ArrayList<>();


    //用于定时任务
    public void syncTask() {

        //所有人员信息
        List<RePersonInfo> rePersonInfos = rePersonInfoMapper.selectNoSyncPerson();

        for (RePersonInfo rePersonInfo : rePersonInfos) {

            //人员是否被删除
            String delFlag = rePersonInfo.getDelFlag();
            try {
                if (delFlag != null && delFlag.equals("1")){
                    deleteRePerson(rePersonInfo.getId());
                }else{
                    updateRePerson(rePersonInfo,"0");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //添加人员到设备
    public void insertRePerson(RePersonInfo rePersonInfo){

        String cardNumber = rePersonInfo.getCardNumber();

        List<Integer> placeId = iReSitePersonnelRelationService.selectSiteById(cardNumber);

        for (Integer id : placeId) {

            List<String> machinelist = iReMachineService.selectReMachineByPlaceId(id);

            for (String code : machinelist) {

                addPerson(code, rePersonInfo);

            }

        }
    }

    //删除人员-设备
    public void deleteRePerson(Long id){

        try {
            RePersonInfo rePersonInfo = selectRePersonInfoById(id);

            String cardNumber = rePersonInfo.getCardNumber();

            List<Integer> placeId = iReSitePersonnelRelationService.selectSiteById(cardNumber);

            for (Integer innerid : placeId) {

                List<String> machinelist = iReMachineService.selectReMachineByPlaceId(innerid);

                for (String code : machinelist) {

                    delPerson(code, id);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新人员-设备
    public void updateRePerson(RePersonInfo rePersonInfo,String maCode){

        try {
            String cardNumber = rePersonInfo.getCardNumber();
            //查询id
            RePersonInfo personInfo = selectRePersonInfoByCardNumber(cardNumber);
            rePersonInfo.setId(personInfo.getId());

            //每个人对应的场所
            List<Integer> placeId = iReSitePersonnelRelationService.selectSiteById(cardNumber);

            for (Integer id : placeId) {

                if (id == null) {
                    continue;//处理错误,场所信息为null
                }
                //场所下的在线设备
                List<String> machinelist = iReMachineService.selectReMachineByPlaceId(id);

                for (String code : machinelist) {

                    if(maCode != null && maCode.equals("0")){
                        if (rePersonInfo.getImgface() == null){
                            upPerson(code, personInfo.getId(), personInfo);
                        }else{
                            upPerson(code, personInfo.getId(), rePersonInfo);
                        }
                    }else{
                        if (code.equals(maCode)){
                            if (rePersonInfo.getImgface() == null){
                                upPerson(code, personInfo.getId(), personInfo);
                            }else{
                                upPerson(code, personInfo.getId(), rePersonInfo);
                            }
                        }
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //更新人员到设备
    private void upPerson(String code,Long id,RePersonInfo rePersonInfo){
        delPerson(code,id);
        addPerson(code,rePersonInfo);
    }

    //从设备删除人员
    private void delPerson(String code,Long id){
        FullHttpRequest httpRequest = null;

        String str = "/V1.0/PeopleLibraries/3/People/" + id + "?LastChange=" + System.currentTimeMillis();
//        String str = "/V1.0/PeopleLibraries/4/People/" + id + "?LastChange=" + System.currentTimeMillis();

        try {
            httpRequest = RequestDeviceManager.createRequestDeviceInfo(str, "", HttpMethod.DELETE);
            HttpKeepAliveManager.getResponseMapByKeepAliveConnection(code, httpRequest);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 添加人员到设备
    private void addPerson(String code,RePersonInfo rePersonInfo){

        //resultList为本次同步的人员列表
        SyncResult syncResult = new SyncResult();
        syncResult.setName(rePersonInfo.getName());
        syncResult.setIdCard(rePersonInfo.getCardNumber());
        syncResult.setMachineCode(code);
        resultList.add(syncResult);

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        FullHttpRequest httpRequest = null;

        Map<String,Object> map = new HashMap<>();
        map.put("Num",1);
        List<Object> personInfoList = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("PersonID",rePersonInfo.getId());
        map1.put("LastChange",System.currentTimeMillis());
        map1.put("PersonCode",rePersonInfo.getId() + "");
        map1.put("PersonName",rePersonInfo.getName());
        map1.put("Remarks","");
        map1.put("TimeTemplateNum",0);
        List<Object> timeTemplateList = new ArrayList<>();

        map1.put("TimeTemplateList",timeTemplateList);
        map1.put("IdentificationNum",1);
        List<Object> identificationList = new ArrayList<>();
        Map<String,Object> map22 = new HashMap<>();
        map22.put("Type",0);//身份证
        map22.put("Number",rePersonInfo.getCardNumber());//身份证
        identificationList.add(map22);

        map1.put("IdentificationList",identificationList);
        map1.put("ImageNum",1);
        List<Object> imageList = new ArrayList<>();
        Map<String,Object> map24 = new HashMap<>();
        map24.put("FaceID",rePersonInfo.getId());
        map24.put("Name",rePersonInfo.getId() + ".jpg");

        //没有图片添加会失败
        if (rePersonInfo.getImgface().length() > 255){
            map24.put("Size",rePersonInfo.getImgface().length() - 23);
            map24.put("Data",rePersonInfo.getImgface().substring(23));
        }else{
            String imgface = filePath + "/" + rePersonInfo.getImgface();
            String strimg = img_base64(imgface);
            map24.put("Size",strimg.length());
            map24.put("Data",strimg);
        }

        imageList.add(map24);
        map1.put("ImageList",imageList);
        personInfoList.add(map1);
        map.put("PersonInfoList",personInfoList);
        String str = JSON.toJSONString(map);

        try {
            httpRequest = RequestDeviceManager.createRequestDeviceInfo(LapiUriConstat.ADD_PERSON, str, HttpMethod.POST);
            Map<String, String> response = HttpKeepAliveManager.getResponseMapByKeepAliveConnection(code, httpRequest);
            String s = JSON.toJSONString(response);
            JSONObject jsonObject = JSON.parseObject(s);

            String string = jsonObject.getJSONObject("Response").getJSONObject("Data").getJSONArray("PersonList")
                    .getJSONObject(0).getJSONArray("FaceList")
                    .getJSONObject(0).getString("ResultCode");

            if (string.equals("0")){
                rePersonInfo.setSyncType("1");
            }else{
                rePersonInfo.setSyncType("3");
            }

            rePersonInfoMapper.updateRePersonInfoByCardNumber(rePersonInfo);

        } catch (Exception e) {
            e.printStackTrace();
            rePersonInfo.setSyncType("2");
            rePersonInfoMapper.updateRePersonInfoByCardNumber(rePersonInfo);
        }
    }


    public static String img_base64(String path) {
        /**
         *  对path进行判断，如果是本地文件就二进制读取并base64编码，如果是url,则返回
         */
        String imgBase64="";
        if (path.startsWith("http")){
            imgBase64 = path;
        }else {
            try {
                File file = new File(path);
                byte[] content = new byte[(int) file.length()];
                FileInputStream finputstream = new FileInputStream(file);
                finputstream.read(content);
                finputstream.close();
                imgBase64 = new String(Base64.encodeBase64(content));
            } catch (IOException e) {
                e.printStackTrace();
                return imgBase64;
            }
        }

        return imgBase64;
    }

}
